package ygw.study.advanced.sort;


import org.junit.Test;
import ygw.study.advanced.sort.common.SortUtils;

/**
 * <p>
 * 插入排序
 * </p>
 * <p>
 * Copyright:.All rights reserved.
 * </p>
 * <p>
 * Company:Zsoft
 * </p>
 * <p>
 * CreateDate: 2021-05-25
 * </p>
 *
 * @author YuGongWen
 * @history Mender: YuGongWen；Date: 2021-05-25；
 */
public class InsertionSort {


    //核心代码---开始
    public static void sort(Comparable[] arr) {
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            // 寻找元素 arr[i] 合适的插入位置
            for (int j = i; j > 0; j--) {
                if (arr[j].compareTo(arr[j - 1]) < 0) {
                    swap(arr, j, j - 1);
                } else {
                    break;
                }
            }
        }
    }

    //核心代码---结束
    public static void swap(Object[] arr, int i, int j) {
        Object t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    @Test
    public void test() {
//        Integer[] arr = SortUtils.gennerateArray(10000,90000000);
        Integer[] arr = SortUtils.gennerateArray(10, 100);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            System.out.print(' ');
        }
        InsertionSort.sort(arr);
        System.out.println("\n排序后");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            System.out.print(' ');
        }
    }

}